<script setup lang="ts">
import {ref, computed,inject} from 'vue'
import {Message} from "@arco-design/web-vue";
import {saveAs} from 'file-saver';
import {dict} from '@/api/system/dict.js';
import feeType from '@/api/finance/feeType.js';
// import dictHelp from "@/utils/dicthelp.js";
import jsonBig from "json-bigint";
import Print from "@/utils/print";
import DataGridNew from "@cps/DataGrid/DataGridNew.vue";

const props = defineProps({
  visible: Boolean,
  crudRef: {
    required: true
  },
  dataList: {
    required: true
  },
  selected: {
    type: Array,
    default: () => []
  },
})
const tableList = inject('tableList');
const columnsDist = inject('columnsDist');
const getDictData = inject('getDictData');


const config = ref({
  title: '',
  data: [],
  api: Function,
  displayDataIndex: '',
  form: {},
  ApiType: undefined,
  isDownload: undefined,
  isPrint: undefined,
})
const form = ref({})
const loading = ref({
  value: false,
  count: 0,
})
const visible = ref()
const records = ref([])
const emit = defineEmits(['cancel'])
const options = computed(() => {
  let defaultOptions = {
    showButtons: false
  }
  return {...defaultOptions, ...config.value.form.options}
})
/*
* @param button
* @param button.title 窗口标题
* @param button.api   接口地址
* @param button.form  表单配置
* @param button.action  自定义方法,优先级高于api
* @param button.displayDataIndex  展示编号的字段,默认 shipment_no > number > name
* */
const open = async (button) => {
  if (!props.selected || props.selected.length == 0) {
    Message.error('至少选择一条数据')
    return;
  }
  if (button.action && typeof button.action === 'function') {
    button.action(props.selected)
    return;
  }
  if (!button.api || ('function' !== typeof button.api && 'function' !== typeof button.api.value)) {
    Message.error('缺少接口配置')
    return;
  }
  let api = typeof button.api === 'object' ? button.api.value : button.api
  config.value.title = 'object' === typeof button.title ? button.title.value : button.title
  config.value.displayDataIndex = button.displayDataIndex ? button.displayDataIndex : ''
  config.value.api = api
  config.value.form = button.form ? button.form : null
  config.value.ApiType = button.ApiType ? button.ApiType : null
  config.value.isDownload = button.isDownload ? button.isDownload : null
  config.value.isPrint = button.isPrint ? button.isPrint : null
  let keyIndex =  config.value.form?.id || 'id'
  // records.value = JSON.parse(JSON.stringify(props.crudRef.getTableData().filter(i => props.selected.includes(i[keyIndex]))))
  records.value=JSON.parse(JSON.stringify(props.dataList.filter(i =>props.selected.includes(i[keyIndex]))))
  console.log('records',records)
  form.value = button.form?.form ? JSON.parse(JSON.stringify(button.form.form)) : {}
  loading.value = {
    value: false,
    count: 0,
  }

  if (config.value.isPrint) {
    const key = config.value.form?.key || 'ids';
    let response = await config.value.api(Object.assign({[key]: props.selected}, form.value))
    if(!response.success){
      // console.log(response)
      Message.error(response.message)
      return;
    }
    content.value = response.data
  }
  visible.value = true
  buttonDisabled.value = false
  let res = await dict.getDict('currencyType')
  res.data.map(i=>{
    currency.value.push(i.title)
    currency_desc.value[i.title] = i.key
  })
  currency.value = []
  // currency_desc.value = []
  res = await feeType.list({})
  res.data.map(i=>{
    fee_type.value.push(i.fee_name)
    fee_type_desc.value[i.fee_name] = i.id
  })
  fee_type.value = []
  // fee_type_desc.value = []
  
  columnsDist.value.dicthelpApi_customer.data.map(i=>{
    user.value.push(i.nick)
    user_desc.value[i.nick] = i.id
  })
  user.value = []

  columnsDist.value.dicthelpApi_service.data.map(i=>{
    service_id.value.push(i.name)
    service_id_desc.value[i.name] = i.id
  })
  service_id.value = []

  columnsDist.value.dicthelpApi_addressLibDetail.data.map(i=>{
    detail_id.value.push(i.name)
    detail_id_desc.value[i.name] = i.code
  })
console.log('service_id_desc.value',service_id_desc.value)
console.log('service_id_desc.value',detail_id_desc.value)


  detail_id.value = []
  userData.value=[]

  records.value.forEach((data, index) => {
    let obj={
      shipment_no:data.shipment_no,
      service_id_desc:getDictData('attrApi','dicthelpApi_service',data.service_id,3,columnsDist.value),
      user_desc:data.user?.nick,
      charge_weight:data.volume_weight?.charge_weight??'',
      parcel_count:renderParcelCount(data),
      client_reference:data?.client_reference??'',
      main_name:data.volume_weight?.main_name??'',
      detail_id_desc:getDictData('attrApi','dicthelpApi_addressLibDetail',data.address.address_lib_detail_id,7,columnsDist.value),
      name: data?.address?.name??'',
      postcode:data.address?.postcode??'',
      business_at: '',
      fee_type_desc: '',
      currency_desc: '人民币',
      unit_desc: 'KG',
      unit_amount: '',
      memo: '',
      remark: '',
      messageMt:'',
    }
    userData.value.push(obj)
    })
}
const renderParcelCount = (record)=>{
  if(!record.volume_weight){
    return ''
  }
  if(record.status == 1 || record.volume_weight.parcel_count == record.volume_weight.parcel_total){
    return record.volume_weight?.parcel_total ??''
  }else{
    return record.volume_weight.parcel_count + '/' + record.volume_weight.parcel_total
  }
}
const getCurrentDate = ()=> {
    const now = new Date();

    const year = now.getFullYear();

    // 注意：JavaScript的月份是从0开始的，所以需要加1
    const month = String(now.getMonth() + 1).padStart(2, '0');

    // 注意：JavaScript的日期也是从1开始的，所以不需要额外处理
    const date = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
}
const cancel = () => {
  form.value = {}
  config.value.form = {}
  visible.value = false
  userData.value=[]
}
defineExpose({
  open,
})
const percent = computed(() => {
  let topercent=loading.value.count / userData.value.length
  return topercent.toFixed(2);
})
const content = ref([])
const buttonDisabled = ref(false)
const submitApi = async ()=>{
  if(loading.value.value){
    Message.warning('数据正在执行中请稍后再试!')
    return false
  }
  if (loading.value.count > 0) {
    cancel()
    return;
  }
  let feeList = userData.value.filter(j=>{
      return j.business_at || j.fee_type_desc || j.currency_desc || j.unit_desc || j.unit_amount || j.unit || j.memo || j.remark || j.shipment_no
    })
  for(let i = 0 ; i < feeList.length; i++){
     if(!feeList[i].shipment_no){
          Message.error('运单号必填')
          return;
     }
     if(!feeList[i].fee_type_desc){
          Message.error('费用类型必填')
          return;
     }
     if(!feeList[i].currency_desc){
          Message.error('币种必填')
          return;
     }
     if(!feeList[i].unit_desc){
          Message.error('单位必填')
          return;
     }
     if(!feeList[i].unit_amount){
          Message.error('单位费用必填')
          return;
     }
     feeList[i].invoices_type = form.value.invoices_type
  }
  console.log('feeList',feeList)

  buttonDisabled.value = true


  // feeList.map(j=>{
  //     j = descToId(fee_type_desc.value,'fee_type',j)
  //     j = descToId(currency_desc.value,'currency',j)
  //     j = descToId(unit_desc.value,'unit',j)
  // })
  let infoList=[]
  loading.value.value = true
  for(let i = 0 ; i <userData.value.length; i++){
    let info=userData.value[i]
    info = descToId(fee_type_desc.value,'fee_type',info)
    info = descToId(currency_desc.value,'currency',info)
    info= descToId(unit_desc.value,'unit',info)
    infoList=[]
    infoList.push(info)
    try {
      for(let j = 0 ; j <records.value.length; j++){
      // records.value.map(j=>{
        let item=records.value[j]
        if(info.shipment_no==item.shipment_no){
          // item.loading = true
          let res = await config.value.api(item.id,{fees:infoList})
          // item.loading = false
          if(res.code==200){
            info.messageMt=res.message
          }else{
            info.messageMt='失败'
          }
        }
     }
    } catch (e) {
      info.messageMt='失败'
    } finally {
        loading.value.count++
      // item.loading = false
    }
  }
  loading.value.value = false
  tableList()
}
const descToId = (list,key,data)=>{
  for(let k in list){
    if(k == data[key+'_desc']){
          data[key] = list[k]
      }
  }
  return data
}

const user=ref([])
const user_desc=ref({})
const service_id=ref([])
const service_id_desc=ref({})
const detail_id=ref([])
const detail_id_desc=ref({})

const fee_type = ref([])
const fee_type_desc = ref({})
const currency = ref([])
const currency_desc = ref({})
const unit = ref(['KG','m³','票'])
const unit_desc = ref({
  'KG':'1',
  'm³':'2',
  '票':'3'
})

const userData = ref([])

 // 自定义校验数字格式
 const myNumeric = (value, callback) => {
  console.log('value',value)
  console.log('callback',callback)

      // if(value) {
      //     if(typeof value !== 'number') {  // 非数字格式
      //         callback(false);
      //     } else {
      //         let str = String(value);
      //         if(str.indexOf('e') != -1){  // 科学计数法
      //             callback(false);
      //         } else if(value > 0 ? (str.split('.')[0].length > 10) : (str.split('.')[0].length > 11)) {  // 小数点前限制10位，这里要考虑是否为负数，负数有负号，要多算一位
      //             callback(false);
      //         } else if(str.split('.')[1] && str.split('.')[1].length > 5){  // 小数点后限制5位
      //             callback(false);
      //         } else {
      //             callback(true);
      //         }
      //     }
      // } else {
      //     callback(true);
      // }
  }

const columns = ref([
{title: '运单号', data: 'shipment_no',required:true,validator:'validate',},
{title: '客户单号', data: 'client_reference',readOnly:true,},
{title: '主品名', data: 'main_name',readOnly:true,width:100,},
  {title: '服务', data: 'service_id_desc',readOnly:true,
    type: 'dropdown',
    source: service_id.value
  },
  {title: '用户', data: 'user_desc',readOnly:true,
    type: 'dropdown',
    source: user.value
  },
  {title: '地址库', data: 'detail_id_desc',readOnly:true,
    type: 'dropdown',
    source: detail_id.value
  },
  {title: '收件人', data: 'name',readOnly:true,display:true,
  },
  {title: '邮编', data: 'postcode',readOnly:true,
  },
  {title: '收费重', data: 'charge_weight',readOnly:true,
  },
  {title: '件数', data: 'parcel_count',readOnly:true,
    type: 'numeric',
  },
  {title: '业务时间', data: 'business_at',type: 'date', dateFormat: 'YYYY-MM-DD HH:mm:ss'},
  {title: '费用类型', data: 'fee_type_desc',required:true,
    type: 'dropdown',
    source: fee_type.value
  },
  {title: '币种', data: 'currency_desc',required:true,
    type: 'dropdown',
    source: currency.value
  },
  {title: '汇率', data: 'unit'},
  {title: '单位', data: 'unit_desc',required:true,
    type: 'dropdown',
    source: unit.value
  },
  {title: '单位费用', data: 'unit_amount',required:true,type:'numeric'},
  {title: '描述', data: 'memo'},
  {title: '备注', data: 'remark'},
  {title: '返回结果', data: 'messageMt'},
])
const checkboxData=ref(['unit','business_at'])
const checkboxList=ref([{
  label:'汇率',
  value:'unit'
},{
  label:'业务时间',
  value:'business_at'
},{
  label:'地址库',
  value:'detail_id_desc'
},{
  label:'收件人',
  value:'name'
},
])
 //多选选中
 const handleChange = (values) => {
  checkboxData.value=values
  }

</script>

<template>
  <a-modal :title="config.title" :visible='visible' @cancel="cancel" width="80%"
           unmount-on-close
           :hide-cancel="loading.count > 0"
           :closable="!loading.value"
           :escToClose="!loading.value">
    <p style="color:red">注：不填写业务时间则使用拣货时间来生成流水</p>
    <br />
    <!-- todo 成功批量反馈增加结果下载    -->
    <div class="" v-if="!config.isDownload && !config.isPrint">
      <a-checkbox-group direction="vertical" style="display: flex;align-items: center;" v-model="checkboxData" @change="handleChange">
        <div style="margin-right: 30px;color: #f00;">列选中的会隐藏该列：</div>
        <a-checkbox style="margin-right: 30px;" v-for="item in checkboxList" :value="item.value" :key="item.value">{{ item.label }}</a-checkbox>
      </a-checkbox-group>
      <a-progress :percent="percent" v-if="loading.count"></a-progress>

      <data-grid-new v-if="userData!=''" :columns="columns" :checkboxData="checkboxData" v-model="userData" :records="records"/>

      <!-- <a-row justify="start" v-for="(item,i) in records"
             class="border align-center justify-center text-center items-center"
             :class="{
      'bg-gray-300':item.loading,
      'bg-green-300':item.success,
      'bg-red-300':!item.success && item.result
           }">
        <a-col :span="2" class="bg-gray-300 h-8 leading-8">{{ i + 1 }}</a-col>
        <a-col :span="14" class="h-8 leading-8">
          {{ item[config.displayDataIndex] || item.shipment_no || item.number || item.name || item.id }}
        </a-col>
        <a-col :span="8" class="h-8 leading-8 overflow-hidden">
          <a-spin v-if="item.loading"></a-spin>
          <div v-else class="overflow-hidden">{{ item.result }}</div>
        </a-col>
      </a-row> -->
    </div>
    <template #footer>
      <a-button v-if="loading.count == 0" @click="visible=false">取消</a-button>
      <a-button type="primary" @click="submitApi()">{{ loading.count > 0 ? '关闭' : '提交' }}</a-button>
    </template>
  </a-modal>
</template>

<style scoped>
@media print {
  .print-break{
    break-after: page;
  }
}
</style>